<?php

namespace App\Logic;

use Illuminate\Support\Facades\Cache;
use Xrjyz\Curl\Curl;

class NowApi
{

    public static function index(){

        /*
         * 汇率接口介绍
         *  1.发送请求
         *      存入缓存 new_api_exchange
         *      存入获取时间 new_api_time
         * 2.进来之后 查看
         * 获取时间大于2分钟
         *  则查询 更新缓存
         * else  取缓存

         *
         * */
        $time = time();
        $new_api_time = Cache::get('new_api_time');
        $new_api_exchange = Cache::get('new_api_exchange');
        if($new_api_exchange && $new_api_time){
            $cha = $time - $new_api_time;
            if($cha > 180){
                //发送请求
                $rate = self::curl();
            }else{
                return s_msg('',$new_api_exchange);
            }


        }else{
            //发送请求
            $rate = self::curl();
        }

        if($rate['status']==="SUCCESS"){
            Cache::set('new_api_time',$time);
            Cache::set('new_api_exchange',$rate['data']);
        }
        return $rate;



    }

    public static function curl(){
        $new_api_config = [
            'url' => 'http://api.k780.com/?app=finance.rate&scur=USD&tcur=CNY&appkey=48225&sign=5ea6da92083aa9e6dcae5ede933fe732&format=json',
        ];
        $curl = new Curl;
        $curl->url($new_api_config['url']);

        if ($curl->error()) {
            return e_msg(300009,$curl->message());
        }

        if($curl->info()['http_code'] == 200){

            $content = $curl->data();
            $info = json_decode($content,true);
            if($info['success']){
                return s_msg('',$info['result']['rate']);
            }else{
                return e_msg(300010,$info['msg']);
            }

        }else{
            return e_msg(300009,'响应异常'.$curl->info()['http_code']);
        }
    }


}





